package com.yjyw.tiexie.activity.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ToastUtils;
import com.yjyw.tiexie.R;
import com.yjyw.tiexie.bean.ActiveJsonBean;
import com.yjyw.tiexie.bean.ImageJsonBean;
import com.yjyw.tiexie.bean.LoginInfo;
import com.yjyw.tiexie.bean.SuccessBaseBean;
import com.yjyw.tiexie.bean.UploadSuccessBean;
import com.yjyw.tiexie.bean.event.WebEvent;
import com.yjyw.tiexie.common.BaseActivity;
import com.yjyw.tiexie.common.net.HandlerCode;
import com.yjyw.tiexie.common.net.NetAPI;
import com.yjyw.tiexie.common.net.NetCallBack;
import com.yjyw.tiexie.util.FileUtils;
import com.yjyw.tiexie.util.GsonUtil;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.PictureSelectorGlideEngine;
import com.yjyw.tiexie.util.SharedPreferencesUtils;
import com.yjyw.tiexie.util.StringUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created on 2019/7/14.
 *
 * @author ${AUTHOR}
 * TODO:
 */
public class WebViewActivity extends BaseActivity implements NetCallBack{
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.web_view)
    BridgeWebView webView;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.vp)
    ViewPager vp;
    private int type;
    private int selectedType;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int themeId = R.style.picture_default_style;

    private List<String> imageBeanList = new ArrayList<>();

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    private Uri imageUri;

    private String url;

    private String curUrl;

    private List<Fragment> fragmentList = new ArrayList<>();

    private Context mContext;

    private String idName;
    private String idNum;

    @Override
    protected int getContentView() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void init() {
        ImmersionBar.with(this).titleBarMarginTop(R.id.web_view).statusBarColor(R.color.white).statusBarDarkFont(true).navigationBarDarkIcon(true).init();
        EventBus.getDefault().register(this);
        mContext = this;
        type = getIntent().getIntExtra("type", 0);
        String title = getIntent().getStringExtra("title");
        if (StringUtil.isEmpty(title)) {
            tvTitle.setText(getIntent().getStringExtra(""));
        } else {
            tvTitle.setText(getIntent().getStringExtra("title"));
        }
        webView.setDefaultHandler(new DefaultHandler());
        webView.setBackgroundColor(0);
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(false);

        webView.setScrollContainer(false);
        WebSettings webSetting = webView.getSettings();

        //不显示webview缩放按钮
        webSetting.setDisplayZoomControls(false);
        webSetting.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.setMixedContentMode(2);
        }


        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);


//        webView.addJavascriptInterface(new JsInterface(this), "android");

        //加载网页 url
        url = getIntent().getStringExtra("url");

        //判断url是不是通告卡或者名人档案，如果是显示分享按钮
        if (url.contains("user/archives") || url.contains("user/modelcard")) {
            ivRight.setVisibility(View.VISIBLE);
        } else {
            ivRight.setVisibility(View.GONE);
        }

        if (url.contains("wallet/invoice/list")) {
            tvRight.setVisibility(View.VISIBLE);
        } else {
            tvRight.setVisibility(View.GONE);
        }

        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
//        webView.setWebViewClient(new MyWebViewClient(webView));

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                getWebTitle();
                super.onReceivedTitle(view, title);
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
//                openImageChooserActivity();
                applyPermissionsLive();
                return true;
            }


        });
        //js 交互
        registerInit();

        webView.loadUrl(url);

        //申请权限
        //获取短信权限基本联系人权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                    } else {
                        //权限被拒绝
                        showMissingPermissionDialog();
                    }
                });


    }


//    class MyWebViewClient extends WVJBWebViewClient {
//        public MyWebViewClient(WebView webView) {
//
//            // support js send
//            super(webView, new WVJBWebViewClient.WVJBHandler() {
//
//                @Override
//                public void request(Object data, WVJBResponseCallback callback) {
//                    Toast.makeText(WebViewActivity.this, "ObjC Received message from JS:" + data, Toast.LENGTH_LONG).show();
//                    callback.callback("Response for message from ObjC!");
//                }
//            });
//            enableLogging();
//        }
//
//        @Override
//        public void onPageFinished(WebView view, String url) {
//            super.onPageFinished(view, url);
//        }
//
//        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            return super.shouldOverrideUrlLoading(view, url);
//        }
//
//    }

    /**
     * 调用相机
     */
    private void takePhoto() {
        // 指定拍照存储位置的方式调起相机
        String filePath = Environment.getExternalStorageDirectory() + File.separator
                + Environment.DIRECTORY_PICTURES + File.separator;
        String fileName = "IMG_" + DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
        imageUri = Uri.fromFile(new File(filePath + fileName));

        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        Intent Photo = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        Intent chooserIntent = Intent.createChooser(Photo, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});

        startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE);
    }


    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    /**
     * BridgeWebView提供给js调用的方法
     */
    private void registerInit() {
        // 登录数据
        webView.registerHandler("getLoginInfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.e("test", "----有参" + data);
                SharedPreferencesUtils.setParam(mContext, "loginInfo", data + "");
                LoginInfo item = (LoginInfo) GsonUtil.getObject(data + "", LoginInfo.class);
                LogUtil.e("token", item.getToken());
                SharedPreferencesUtils.setParam(mContext, "onceToken", item.getToken() + "");
                SharedPreferencesUtils.setParam(mContext, "userId", item.getCustomerId() + "");
                //根据token获取sign
                getSign();
            }
        });

        webView.registerHandler("getUidToken", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String json = (String) SharedPreferencesUtils.getParam(mContext, "loginInfo", "");
                LogUtil.e("loginInfo", json);
                if (StringUtil.isEmpty(json)) {
                    json = "";
                }
                function.onCallBack(json);
            }
        });

        webView.registerHandler("loginOut", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //token过期退出登录
                SharedPreferencesUtils.clear(WebViewActivity.this);
            }
        });





        webView.registerHandler("goBack", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (webView.canGoBack()) {
                            onWebViewGoBack();
                        } else {
                            finish();
                        }
                    }
                });
            }
        });

    }




    /**
     * 提供给js调用的方法
     */
    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        //在js中调用window.android.getLoginInfo()，便会触发此方法。
        @JavascriptInterface
        public void getLoginInfo(String data) {
            LogUtil.e("test", "----有参" + data);
            SharedPreferencesUtils.setParam(mContext, "loginInfo", data + "");
            LoginInfo item = (LoginInfo) GsonUtil.getObject(data + "", LoginInfo.class);
            LogUtil.e("token", item.getToken());
            SharedPreferencesUtils.setParam(mContext, "onceToken", item.getToken() + "");
            SharedPreferencesUtils.setParam(mContext, "userId", item.getCustomerId() + "");

            //根据token获取sign
            getSign();
        }

        @JavascriptInterface
        public String getUidToken(String data) {
            String json = (String) SharedPreferencesUtils.getParam(mContext, "loginInfo", "");
            LogUtil.e("loginInfo", json);
            if (StringUtil.isEmpty(json)) {
                json = "";
            }
            return json;
        }


        @JavascriptInterface
        public void downloadImageUrl(String data) {
            LogUtil.e("data", data);
            data = GsonUtil.fromJson(data, String.class);

            if ("http://img.bjmdbkj.com/uploadtest/20211130/LrQZTUnlCbKyKy87.JPEG".equals(data)) {
                LogUtil.e("downloadImageUrl", "true");
            } else {
                LogUtil.e("downloadImageUrl", "false");
                LogUtil.e("data", data);
            }
            downloadImg(data);
        }


        @JavascriptInterface
        public void goBack(String data) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (webView.canGoBack()) {
                        onWebViewGoBack();
                    } else {
                        finish();
                    }
                }
            });
        }

        @JavascriptInterface
        public void gotoActivity(String data) {
            LogUtil.e("gotoActivity", data + "");
            ActiveJsonBean jsonBean = (ActiveJsonBean) GsonUtil.getObject(data, ActiveJsonBean.class);
            //type 1去模卡
            switch (jsonBean.getType()) {
            }
        }
    }


    private void getSign() {
        HashMap map = new HashMap();
        get(map, NetAPI.GET_SIGN, HandlerCode.GET_SIGN, this);
    }


    private void getWebTitle() {
        WebBackForwardList forwardList = webView.copyBackForwardList();
        WebHistoryItem item = forwardList.getCurrentItem();
        if (item != null) {
            tvTitle.setText(item.getTitle());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack()) {
            onWebViewGoBack();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            onWebViewGoBack();
        } else {
            exit();
        }
    }

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    private void onWebViewGoBack() {
        webView.goBack();
    }
//    private void onWebViewGoBack() {
//        webView.goBack();
//        getWebTitle();
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
//        AndroidBug5497Workaround.assistActivity(this);
    }

    @Subscribe
    public void refreshData(WebEvent event) {
        switch (event.getType()) {
            case 1:
                String result = event.getMessage();
                LogUtil.e("refreshData", result + "");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        webView.callHandler("authCallBack", result, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {

                            }
                        });
                    }
                });

                break;

            //case 2:
//                //给h5
//                //上传完给h5
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        webView.evaluateJavascript("javascript:onReceiveImageUrl('" + event.getMessage() + "')", new ValueCallback<String>() {
//                            @Override
//                            public void onReceiveValue(String value) {
//                                //value即为js返回值
//                                LogUtil.e("value", value + "");
//                            }
//                        });
//                    }
//                });
//                break;
        }
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (webView != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = webView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(webView);
            }
            webView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.clearView();
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }

    @Override
    public void onResponse(boolean flag, int requestCode, String result) throws Exception {
        switch (requestCode) {
            case HandlerCode.GET_SIGN:
                SuccessBaseBean successBaseBean = (SuccessBaseBean) GsonUtil.getObject(result, SuccessBaseBean.class);
                if (successBaseBean.getCode() == 200) {
                    String userSign = successBaseBean.getMsg();
                    SharedPreferencesUtils.setParam(this, "userSign", userSign + "");
                } else {
                    toast(successBaseBean.getMsg() + "");
                }
                break;
            case HandlerCode.UPLOAD_FILE:
                hideProgressNoMiss();
                UploadSuccessBean uploadSuccessBean = (UploadSuccessBean) GsonUtil.getObject(result, UploadSuccessBean.class);
                if (uploadSuccessBean.getRetcode() == 200) {
                    //上传成功返回url
                    if (uploadSuccessBean.getData() != null) {
                        count++;
                        String imageUrl = uploadSuccessBean.getData().getUrl();
                        imageBeanList.add(imageUrl);
                        uploadFile();
                    }
                } else {
                    toast(uploadSuccessBean.getMsg() + "");
                }
                break;
        }
    }

    @Override
    public void tokenTimeOut(int requestCode) {

    }




    @OnClick({R.id.iv_left, R.id.iv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left:
                if (webView.canGoBack()) {
                    //判断包不包含wallet/cashWithdraw 直接关掉
                    if ("收入提现".equals(tvTitle.getText().toString())) {
                        finish();
                    } else {
                        onWebViewGoBack();
                    }
                } else {
                    finish();
                }
                break;
            case R.id.iv_right:
                if (!StringUtil.isWxInstall(this)) {
                    toast(" 请安装微信");
                    return;
                }
                new ShareAction((Activity) this)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .withText(url + "&type=share")//链接，标题 ，描述，图片
                        .setCallback(umShareListener).share();
                break;
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
//            Toast.makeText(context_, "成功分享", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            toast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            toast("分享取消了");
        }
    };

    private void pickMedia(int type, int maxNum, int code) {
        int chooseMode = PictureMimeType.ofImage();
        switch (type) {
            case 1:
                chooseMode = PictureMimeType.ofImage();
                break;
            case 2:
                chooseMode = PictureMimeType.ofVideo();
                break;
            case 3:
                chooseMode = PictureMimeType.ofAll();
                break;
        }
        PictureSelector.create(WebViewActivity.this)
                .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .loadImageEngine(PictureSelectorGlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                .isWeChatStyle(false)// 是否开启微信图片选择风格
                .isWithVideoImage(false)// 图片和视频是否可以同选,只在ofAll模式下有效
                .maxSelectNum(maxNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .maxVideoSelectNum(1) // 视频最大选择数量，如果没有单独设置的需求则可以不设置，同用maxSelectNum字段
                .imageSpanCount(3)// 每行显示个数
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                .previewImage(true)// 是否可预览图片
                .previewVideo(true)// 是否可预览视频
                .enablePreviewAudio(true) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .compress(true)// 是否压缩
                .compressQuality(80)// 图片压缩后输出质量 0~ 100
                .synOrAsy(true)//同步false或异步true 压缩 默认同步
                .compressFocusAlpha(false)//不要alpha channel
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(true)// 是否显示gif图片
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                .videoMaxSecond(300)
                .cutOutQuality(90)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .recordVideoSecond(300)//录制视频秒数 默认60s
                .setMaxZoneImageSize(5)
                .forResult(code);//结果回调onActivityResult code
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                if (resultCode == RESULT_OK) {
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia localMedia : selectList) {
                        if (!StringUtil.isEmpty(localMedia.getCompressPath())
                                && ("/".equals(localMedia.getCompressPath()) || localMedia.getCompressPath().length() == 1)) {
                            localMedia.setCompressPath(FileUtils.getRealPath(this, localMedia.getPath()));
                        } else {
                            localMedia.setCompressPath(FileUtils.getRealPath(this, localMedia.getPath()));
                        }

                    }
                    if (selectList.size() > 0) {
                        //选完就要上传
                        //上传图片
                        count = 0;
                        imageBeanList.clear();
                        uploadFile();
                    }
                }
                break;
            case FILE_CHOOSER_RESULT_CODE:
                if (null == uploadMessage && null == uploadMessageAboveL) return;
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (uploadMessageAboveL != null) {
                    chooseAbove(resultCode, data);
//                    onActivityResultAboveL(requestCode, resultCode, data);
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(result);
                    uploadMessage = null;
                }
                break;
        }

    }

    private void applyPermissionsLive() {
        //获取短信权限基本联系人权限
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        takePhoto();
                    } else {
                        //权限被拒绝
                        showMissingPermissionDialog();
                    }
                });
    }

    /**
     * 提示用户的 dialog
     */
    protected void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少权限。会导致部分功能无法使用！\n\n请点击\"设置\"-\"权限\"-打开所需权限。");
        // 拒绝, 退出应用
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("info", "8--权限被拒绝,此时不会再回调onRequestPermissionsResult方法");
                    }
                });
        builder.setPositiveButton("设置",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i("info", "4,需要用户手动设置，开启当前app设置界面");
                        startAppSettings();
                    }
                });
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 打开 App设置界面
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * Android API >= 21(Android 5.0) 版本的回调处理
     *
     * @param resultCode 选取文件或拍照的返回码
     * @param data       选取文件或拍照的返回结果
     */
    private void chooseAbove(int resultCode, Intent data) {
        Log.e("WangJ", "返回调用方法--chooseAbove");

        if (RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对从文件中选图片的处理
                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
                    results = new Uri[]{uriData};
                    for (Uri uri : results) {
                        Log.e("WangJ", "系统返回URI：" + uri.toString());
                    }
                    uploadMessageAboveL.onReceiveValue(results);
                } else {
                    uploadMessageAboveL.onReceiveValue(null);
                }
            } else {
                Log.e("WangJ", "自定义结果：" + imageUri.toString());
                uploadMessageAboveL.onReceiveValue(new Uri[]{imageUri});
            }
        } else {
            uploadMessageAboveL.onReceiveValue(null);
        }
        uploadMessageAboveL = null;
    }

    private void updatePhotos() {
        // 该广播即使多发（即选取照片成功时也发送）也没有关系，只是唤醒系统刷新媒体文件
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(imageUri);
        sendBroadcast(intent);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    private int count;

    private void uploadFile() {
        //count 先从第0个开始上传 上传成功了以后 count++  判断count如果大于
        if ((count + 1) > selectList.size()) {
            ImageJsonBean imageJsonBean = new ImageJsonBean();
            imageJsonBean.setUrl(imageBeanList);
            imageJsonBean.setSelectedType(selectedType);
            String json = GsonUtil.getJson(imageJsonBean);
            //图片上传结束
            LogUtil.e("ImageJsonBean", json);
            hideProgressNoMiss();
            doAction(json);
            return;
        }
        //如果是编辑 需要判断http不上传
        if (selectList.get(count).getCompressPath().contains("http")) {
            String imageUrl = selectList.get(count).getCompressPath();
            count++;//0->1
            imageBeanList.add(imageUrl);
            uploadFile();
            return;
        }
        showProgressNoMiss("");
        File file = new File(selectList.get(count).getCompressPath()); //生成文件
        HashMap map = new HashMap();
        postFile(map, NetAPI.UPLOAD_FILE, HandlerCode.UPLOAD_FILE, file, this);
    }

    private void doAction(String json) {
        //上传完给h5
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript("javascript:onReceiveImageUrl('" + json + "')", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {
                        //value即为js返回值
                        LogUtil.e("value", value + "");
                    }
                });
            }
        });
    }


    private boolean isDownlading;

    private void downloadImg(String imgUrl) {
        if (!isDownlading) {
            //如果不是正在下载，则开始下载
            isDownlading = true;
            new DownloadImgTask(0).execute(imgUrl);
        }
    }

    @SuppressLint("StaticFieldLeak")
    class DownloadImgTask extends AsyncTask<String, Integer, Void> {

        private int mPosition;

        public DownloadImgTask(int position) {
            mPosition = position;
        }

        @Override
        protected Void doInBackground(String... params) {
            String imgUrl = params[0];
            File file = null;
            try {
                FutureTarget<File> future = Glide
                        .with(WebViewActivity.this)
                        .load(imgUrl)
                        .skipMemoryCache(true) // 不使用内存缓存
                        .diskCacheStrategy(DiskCacheStrategy.NONE) // 不使用磁盘缓存;
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                file = future.get();

                String filePath = file.getAbsolutePath();
                String destFileName = System.currentTimeMillis() + FileUtils.getImageFileExt(filePath);
                File destFile = new File(FileUtils.getDir(""), destFileName);

                FileUtils.copy(file, destFile);// 保存图片

                // 最后通知图库更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(new File(destFile.getPath()))));
            } catch (Exception e) {
                LogUtil.e("WebActivity", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            isDownlading = false;
            ToastUtils.s(WebViewActivity.this, "保存成功");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
//         KLog.i(TAG,"progress: " + values[0]);
        }
    }

}
